<?php
namespace app\mp\admin;
use app\system\admin\Admin;
use jinpeng\Jinpeng;
use app\common\service\Order as OrderService;
/**
 * sku款式工艺工价管理
 * @author sparkguo
 */
class ProcessPrice extends Admin
{

    public function initialize() {
    	parent::initialize();
    }

    /**
     *sku工艺工价列表
     * @return string|json
     */
    public function index(){
        $factoryKV = getFactoryKV(false);
        $processStage=['1'=>'裁床','2'=>'车间','3'=>'尾部'];
        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $factoryId   = $this->request->param('factory_id/d', 0);
            $client_ordernum   = $this->request->param('client_ordernum', '');
            $sku = $this->request->param('sku', '');
            $process_name=$this->request->param('process_name','');
            $process_price=$this->request->param('process_price','');
            $process_stage=$this->request->param('process_stage','');

            $where=$orderWhere=$skupriceWhere=[];
            if ($export) {
                set_time_limit(0);
                $page = 1;$limit = 99999;
            }
            if($process_stage) $where[] =$skupriceWhere[]= ['sku_price.process_stage', '=', $process_stage];
            if($process_name) $where[] =$skupriceWhere[]= ['sku_price.process_name', '=', $process_name];
            if($process_price) $where[] = $skupriceWhere[]= ['sku_price.process_price', '=', $process_price];
            if($sku) $where[] = ['sk.sku', '=', $sku];
            if($factoryId) $orderWhere[] = ['factory_id', '=', $factoryId];

            if(!empty($client_ordernum)){
                $orderWhere[]=['client_ordernum','eq',$client_ordernum];
            }
            if($orderWhere!=[]){
                //$orderWhere[]=['status','<',2];//增加未结束的订单才查询出来
                $order_sku=db('order o')->where($orderWhere)->column("sku");
                if(!empty($order_sku)) $where[] = ['sk.sku', 'in', $order_sku];
            }
            $total = db('sku sk')->join('sku_process_price sku_price', 'sku_price.sku = sk.sku','left')->where($where)->group('sk.sku')->count(1);
            $list = db('sku sk')->join('sku_process_price sku_price', 'sku_price.sku = sk.sku','left')
                ->where($where)->page($page)->field("sk.*,sum(sku_price.process_price) as sku_process_price,sk.pic,sk.price,sku_price.update_time,sku_price.upload_to_golds,sku_price.upload_jp_time")
                ->group('sk.sku')->limit($limit)->order('sku_price.update_time desc,sk.id desc')->select();
            if($total>0){
                $sku_id_arr=array_column($list,'sku');
                $processPricelist=db("sku_process_price sku_price")->where([['sku','in',$sku_id_arr]])->field("*")->where($skupriceWhere)->order('process_stage asc,id asc')->select();
                $processStageCounts=db("sku_process_price sku_price")->where([['sku','in',$sku_id_arr]])->field("count(id) as stagecount,process_stage,sku,update_time")->where($skupriceWhere)
                    ->order('process_stage asc')->group('sku,process_stage')->select();
                $customerProcessPrice=db('order o')->join('order_ext ext', 'o.id = ext.order_id','left')
                    ->field("sku,ext.cost")->where([['sku','in',$sku_id_arr],['cost','>',0]])->group("o.sku")->order("o.id desc")->select();
                $custPirceArr=arrayByKey($customerProcessPrice,'sku');
                $sku_index_arr=[];
                foreach ($processPricelist as $processPriceInfo){
                    $sku_index_arr[$processPriceInfo['sku']][$processPriceInfo['process_stage']][]=$processPriceInfo;
                }
                $stageCountsArr=[];
                foreach ($processStageCounts as $stageinfo){
                    $stageCountsArr[$stageinfo['sku']][$stageinfo['process_stage']]=$stageinfo;
                }
                foreach($list as &$skuInfo){
                    $customerProcessPrice=db('order o')->join('order_ext ext', 'o.id = ext.order_id','left')
                        ->field("sku,ext.cost")->where([['sku','in',$sku_id_arr],['cost','>',0]])->order("o.id desc")->value("cost");
                    $skuInfo['cost']=isset($custPirceArr[$skuInfo['sku']]['cost']) ? $custPirceArr[$skuInfo['sku']]['cost'] :0;
                    $skuInfo['processPre']= $skuInfo['cost']<=0 ? '100.00': sprintf("%.2f",$skuInfo['sku_process_price'] / $skuInfo['cost']*100);
                    $skuInfo['processPriceInfo']=isset($sku_index_arr[$skuInfo['sku']]) ? $sku_index_arr[$skuInfo['sku']] :[] ;
                    $skuInfo['processStage']=$processStage;
                    $skuInfo['processStageCounts']=isset($stageCountsArr[$skuInfo['sku']]) ? $stageCountsArr[$skuInfo['sku']] :[] ;
                    $skuInfo['search_processstage']=$process_stage;
                }
            }
            $totaldata= 0;
            $data = [];
            $data['totaldata']=$totaldata;
            $data['data'] = $list;
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            $data['processstage']=$processStage;
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $processNames=db("sku_process_price")->distinct("process_name")->column("process_name",'process_name');

        $assign = [
            'process_stages'=>['' => '请选择']+$processStage,
            "process_name"=>$processNames,
            'factoryKV' => ['' => '请选择'] + $factoryKV
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * @author sparkguo
     * 设置工艺工价
     */
    public function editProcessPrice(){
        $action=$this->request->param('action');
        $editsku   = $this->request->param('sku', 0);
        $stage= $this->request->param('stage', '');
        $uploadToJinP=$this->request->param('uploadToJinP', '');
        $where=[];
        $where[]=['process_stage','eq',$stage];
        $where[]=['sku','=',$editsku];
        $stageArr=['','裁床','车间','尾部'];
        if($action=='dosave'){
            $dataIdArr=$this->request->param('data_id',[]);
            $process_name=$this->request->param('process_name',[]);
            $process_name_id=$this->request->param('process_name_id',[]);
            $process_price=$this->request->param('process_price',[]);
            $oldProcessPriceList=db("sku_process_price")->where($where)->select();
            $oldPriceList=$this->_getIdKeyArray($oldProcessPriceList,'id');
            $needDelPriceIds=array_column($oldPriceList,'id','id');
            if ($stage == 1 && count($dataIdArr) > 1) {
                //return $this->Json(0, '裁床只能设置一条，操作失败');
            }
            try {
                db()->startTrans();
                foreach($dataIdArr as $key=>$dataid){
                    $insetData=['sku'=>$editsku,'process_name'=>$process_name[$key],'process_stage'=>$stage,'process_name_id'=>$process_name_id[$key],
                        'process_price'=>$process_price[$key],'create_time'=>time(),'update_time'=>time(),'remark'=>'','admin_id'=>ADMIN_ID];
                    if(empty($dataid)){
                        //处理新增
                        $process_price_id=db("sku_process_price")->insertGetId($insetData);
                        $insetData['process_price_id']=$process_price_id;
                        $insetData['update_time']=time();
                        $insetData['status_action']=0;
                        db("sku_process_price_log")->insert($insetData);
                    }else{
                        //处理修改
                        unset($insetData['create_time']);
                        if($oldPriceList[$dataid]['process_price']!=$insetData['process_price'] || $oldPriceList[$dataid]['process_name_id']!=$insetData['process_name_id']){
                            db("sku_process_price")->where('id','eq',$dataid)->update($insetData);
                            $insetData['update_time']=time();
                            $insetData['create_time']=time();
                            $insetData['process_price_id']=$dataid;
                            $insetData['status_action']=1;
                            db("sku_process_price_log")->insert($insetData);
                        }
                        if(isset($needDelPriceIds[$dataid])){
                            unset($needDelPriceIds[$dataid]);
                        }
                    }
                }
                //处理删除
                if(count($needDelPriceIds)>0){
                    foreach ($needDelPriceIds as $k=>$v){
                        $insetData= db("sku_process_price")->where([['id','=',$v]])->find();
                        $insetData['update_time']=time();
                        $insetData['create_time']=time();
                        $insetData['process_price_id']=$insetData['id'];
                        $insetData['status_action']=10;
                        $insetData['admin_id']=ADMIN_ID;
                        unset($insetData['id']);unset($insetData['upload_jp_time']);
                        db("sku_process_price_log")->insert($insetData);
                        db("sku_process_price")->where([['id','=',$v]])->delete();//update(['status'=>99])
                    }
                }
                $resData=[];
                if($uploadToJinP==1){  //同步工价到金鹏
                    $putret=$this->_updateToJinp($editsku,$stage);
                    $resData=$putret;
                }
                db()->commit();
                return $this->Json(1, $msg='', $resData);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }else{
            $processPriceList=db("sku_process_price")->where([['sku','=',$editsku],['process_stage','eq',$stage]])->field("*")->order('id asc')->select();
            $processNaneRet=db("proces_name_list")->where([['process_stage','eq',$stage]])->field("*")->order('id asc')->select();
            $processNameList=array_column($processNaneRet,'process_name','id');
            if(empty($editsku)) {
                $this->error('请选择要编辑的sku');
            }
            $assign = [
                'sku'=>$editsku,
                'processNameList'=>$processNameList,
                'stagelist'=>$stageArr,
                'stage'=>$stage,
                'datalist'=>$processPriceList,
                'factoryKV' => ['' => '请选择']
            ];
            return $this->assign($assign)->fetch();
        }
    }

    //工序价格更新同步至金鹏
    private function _updateToJinp($editsku,$stage){
        $jp=new Jinpeng();
        /*$where=[];
        $where[]=['process_stage','eq',$stage];
        $where[]=['sku','=',$editsku];
        $processPriceList=db("sku_process_price")->where($where)->select();
        $newProcessList=[];
        foreach ($processPriceList as $key=>$item){
            $newProcessList[]=['id'=>$item['id'],'sku'=>$item['sku'],'process_name'=>$item['process_name'],'process_stage'=>$item['process_stage'],'process_price'=>$item['process_price']];
        }
        $res1=$jp->synSkuProcess($editsku,$newProcessList);
        $jinpengStatus=2; //同步失败状态
        if($res1['succeed']==true) $jinpengStatus=1; //同步成功
        $a=db('sku_process_price')->where($where)->update(['upload_to_golds'=>$jinpengStatus,'update_time'=>time()]);			//dump($a);*/
        $oInfo=db("order")->where([['sku','=',$editsku],['jinpeng_status','>',0]])->order('id desc')->find();
        if(empty($oInfo)){
            return ['data' =>'同步失败' ,'succeed' =>false,'msg' =>'同步失败，未找到已同步至金鹏的订单'];
        }
        $orderService= new OrderService();
        $putRet=$orderService->syncPutSkuProcessListToJP($oInfo['sku'],$oInfo['id'],$oInfo['client_ordernum'],'ProcessEditPut');
        return $putRet;
    }

    //工价修改日志
    public function processPriceLog(){
        $systemUserKV = getSystemUserKV(null);
        $editsku   = $this->request->param('sku', 0);
        $stage= $this->request->param('stage', '');
        $where=[];
        $where[]=['process_stage','eq',$stage];
        $where[]=['sku','=',$editsku];
        $stageArr=['','裁床','车间','尾部'];
        $processPriceList=db("sku_process_price_log")->where([['sku','=',$editsku],['process_stage','eq',$stage]])->field("*")->order('id desc')->select();
        if(empty($editsku)) {
            $this->error('请选择要查看的sku');
        }
        foreach ($processPriceList as $key => &$item) {
            $item['create_time'] = date("Y-m-d H:i:s", $item['create_time']);
            @$item['actionuser'] = $systemUserKV[$item['admin_id']];
            $processPriceList[$key]['status_action_txt'] = '新增';
            switch ($item['status_action']) {
                case 0:
                    $processPriceList[$key]['status_action_txt'] = '新增';
                    break;
                case 1:
                    $processPriceList[$key]['status_action_txt'] = '修改';
                    break;
                case 10:
                    $processPriceList[$key]['status_action_txt'] = '删除';
                    break;
            }
        }
        $assign = [
            'sku'=>$editsku,
            'stagelist'=>$stageArr,
            'stage'=>$stage,
            'datalist'=>$processPriceList,
            'factoryKV' => ['' => '请选择']
        ];
        return $this->assign($assign)->fetch();
    }

    //返回由keyname下标组成的新数组
    private function _getIdKeyArray($array,$keyname='id'){
        $newArray=[];
        foreach ($array as $index=>$item){
            $newArray[$item[$keyname]]=$item;
        }
        return $newArray;
    }



    public function sysUpdatePrice(){
        set_time_limit(0);
        $orderService= new OrderService();
        //$putRet=$orderService->insertProcessMemoData('sf2201123332752717');
       /* $skuProcessPriceList=db('sku sk')->join('sku_process_price sku_price', 'sku_price.sku = sk.sku','left')
            ->where('sku_price.id is null and (chewei_price >0 or sixian_price >0 or zhuanji_price>0)')
            ->field("sk.id,sk.sku,sk.chewei_price,sk.sixian_price,sk.zhuanji_price,  sku_price.update_time")
            ->group('sk.sku')->order('sk.id asc')->select();
        if(empty($skuProcessPriceList)) {
            $this->error('have no notempty sku data price');
        }
        foreach ($skuProcessPriceList as $key => &$item) {
            echo $key; print_r($item);echo "<br>";
            if($item['chewei_price']>0){
                $insetData=['sku'=>$item['sku'],'process_name'=>'车位','process_stage'=>2,'process_name_id'=>10,
                    'process_price'=>$item['chewei_price'],'create_time'=>time(),'update_time'=>time(),'remark'=>'','admin_id'=>106];
                if(empty($dataid)){
                    //处理新增
                    $process_price_id=db("sku_process_price")->insertGetId($insetData);
                    $insetData['process_price_id']=$process_price_id;
                    $insetData['update_time']=time();
                    $insetData['status_action']=0;
                    db("sku_process_price_log")->insert($insetData);
                }
            }
            if($item['sixian_price']>0){
                $insetData=['sku'=>$item['sku'],'process_name'=>'打边','process_stage'=>2,'process_name_id'=>11,
                    'process_price'=>$item['sixian_price'],'create_time'=>time(),'update_time'=>time(),'remark'=>'','admin_id'=>106];
                if(empty($dataid)){
                    //处理新增
                    $process_price_id=db("sku_process_price")->insertGetId($insetData);
                    $insetData['process_price_id']=$process_price_id;
                    $insetData['update_time']=time();
                    $insetData['status_action']=0;
                    db("sku_process_price_log")->insert($insetData);
                }
            }
            if($item['zhuanji_price']>0){
                $insetData=['sku'=>$item['sku'],'process_name'=>'冚车','process_stage'=>2,'process_name_id'=>12,
                    'process_price'=>$item['zhuanji_price'],'create_time'=>time(),'update_time'=>time(),'remark'=>'','admin_id'=>106];
                if(empty($dataid)){
                    //处理新增
                    $process_price_id=db("sku_process_price")->insertGetId($insetData);
                    $insetData['process_price_id']=$process_price_id;
                    $insetData['update_time']=time();
                    $insetData['status_action']=0;
                    db("sku_process_price_log")->insert($insetData);
                }
            }
        }*/
    }

    /**
     * 成衣库存明细
     * @return string|json
     * @author sparkguo
     */
    public function skuStockLog(){
        $search_param=$this->request->param();
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $export     = $this->request->param('export/d', 0);
        $search_param['showtype']=$this->request->param('showtype');
        $factoryId   = $this->request->param('factory_id/d', 0);
        $search_param['sku']=$this->request->param('sku','');
        $stock_stop_update=$this->request->param('over_time_range');
        $client_ordernum=$this->request->param('client_ordernum');
        $stock_action=$this->request->param('action');

        $factoryKV = getFactoryKV(false);
        $factoryIdarr=array_keys($factoryKV);
        $where[] = ['factory_id','in',$factoryIdarr];
        if(!empty($search_param['sku'])){
            $where[] = ['sku', 'like',$search_param['sku']."%"];
        }
         if($stock_stop_update) $where[] = ['create_time', '<=', strtotime($stock_stop_update." 23:59:59")];
        if($factoryId) $where[] = ['factory_id', '=', $factoryId];
        if($client_ordernum) $where[] = ['client_ordernum', '=', $client_ordernum];
        if($stock_action) $where[] = ['action_type', '=', $stock_action];
        $actiontype=['','入库','出库','盘点'];
        if ($this->request->isAjax()|| $this->request->param('export')) {
            $systemUserKV = getSystemUserKV(null);
            $total=db('sku_stock_log stlog')->where($where)->count(1);
            $dataorderval=$search_param['showtype']=='only_one_sku'?"factory_id desc,create_time desc":'create_time desc';
            $stock_log_list = db('sku_stock_log stlog')->where($where)->page($page)->field("*")->limit($limit)->order($dataorderval)->select();
            if($total>0){
                $sku_id_arr=array_column($stock_log_list,'sku');
                $sku_pic_list=db("sku")->where([['sku','in',$sku_id_arr]])->field("pic,sku")->select();
                $sku_index_arr=array_column($sku_pic_list,'pic','sku');
            }
            foreach($stock_log_list as &$logval){
                $logval['available_detail_arr']=json_decode($logval['available_detail']);
                $logval['defective_detail_arr']=json_decode($logval['defective_detail']);
                @$logval['factory_name']=$factoryKV[$logval['factory_id']];
                $logval['action']=$actiontype[$logval['action_type']];
                @$logval['actionuser']=$systemUserKV[$logval['uid']];
                $logval['pic']=$sku_index_arr[$logval['sku']];
            }
            $data = ['data'=>$stock_log_list,'count'=>$total,'code'=>0,'msg'=>'success'];
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            return json($data);
        }
        $assign = [
            'searchdata'=>$search_param,'factoryKV' => ['' => '请选择'] + $factoryKV,'actionArr'=>['请选择','入库','出库','盘点']
        ];
        return $this->assign($assign)->fetch();
    }

    function exportSkuStockXls($fileName, &$data) {
        $head = ['SKU','生产工厂','所属帐号','最后更新日期','库存总数','尺码库存'];
        $params = [];

        $exportdata = [];
        foreach ($data as $k => $v) {
            $size_countstr='';
            foreach ( $v['factory_stock'] as $key=>$size_stock){
                $size_countstr.=$size_stock['size_name'].":".$size_stock['size_count']."，";
            }
            $exportdata[] = [
                $v['sku'],
                $v['factory_stock'][0]['factory'],
                $v['factory_stock'][0]['account'],
               // "<img src='".$v['pic']."' width='30'>",
                $v['update_time']==0 ? '':date('Y-m-d', $v['update_time']),
                $v['available_count'],
                $size_countstr
            ];
        }
        $params['file'] = $fileName;
        $params['sheet'] = [
            [
                'head' => $head, // 表头
                'data' => $exportdata,
            ],
        ];
        unset($data);
        plugins_run('excel/excel/export', $params);
    }
}